'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 装备升级
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var _ = require('lodash');
var Code = require('../../../../consts/code');
var moduleType = require('../../../../consts/moduleType');
var operationType = require('../../../../consts/operationType');
var equipConf = require('../../../../config/equipConf');
var roleService = require('../../../../services/roleService');
var taskService = require('../../../../services/taskService');
var PlayerManager = require('../../../../libs/playerManager');
var roleService = require('../../../../services/roleService.js');

module.exports = function (msg, session, next) {
    var role_id = session.uid;
    var equip_id = msg.equip_id;
    var num = msg.num || 1;

    if (!equip_id) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }
    // jshint maxstatements:100
    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['role', 'bag', 'task', 'daily_task', 'achieve', 'skill', 'build', 'sevenDayActivity', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var role_model = player_manager.role;
                var bag_model = player_manager.bag;

                // 判断背包是否存在
                var equip = bag_model.getEquip(equip_id);

                if (!equip) {
                    return next(null, {
                        code: Code.BAG_ITEM_NOT_EXIST
                    });
                }

                var role_lv = role_model.getLv();
                for (var i = 0; i < num; i++) {
                    var refine_lv = equip.getRefineLv();

                    // 是否可以升级
                    if (equip.is_advanced == 1) {
                        return next(null, {
                            code: Code.BAG_EQUIP_NOT_UPGRADE_LV
                        });
                    }

                    // 设置进阶标志
                    var is_advanced = _getUpgradeAdvanced(refine_lv + 1) || 0;
                    equip.setAdvanced(is_advanced);

                    // 判断是否精炼等级已经达上限
                    if (refine_lv >= role_lv) {
                        return next(null, {
                            code: Code.BAG_EQUIP_LV_MAX
                        });
                    }

                    // 取出锻造配置信息
                    var forge_conf = equipConf.getEquipLvConf(equip.refine_lv + 1);

                    if (!forge_conf) {
                        return next(null, {
                            code: Code.BAG_ITEM_EQUIP_ADV_CONF_ERROR
                        });
                    }

                    // 消耗锻造材料
                    for (var i1 = 1; i1 <= 5; i1++) {
                        var prop_key = 'property_' + i1.toString();
                        var num_key = 'num_' + i1.toString();

                        if (!forge_conf[prop_key] || !forge_conf[num_key]) {
                            continue;
                        }

                        if (!bag_model.subProperty(forge_conf[prop_key], forge_conf[num_key])) {
                            return next(null, {
                                code: Code.BAG_PROPERTY_NOT_ENOUGH
                            });
                        }
                    }

                    var refine_gold = _getRefineNeedGold(refine_lv + 1);
                    if (!roleService.subGold(player_manager, moduleType.MDL_EQUIP, operationType.OPR_EQUIP_FORGE, refine_gold)) {
                        return next(null, {
                            code: Code.USER_GOLD_NOT_ENOUGH
                        });
                    }

                    // 升级装备
                    equip.addRefineLv();
                }

                // 加入统计开服7天全部达英雄 装备 达到10级
                var bag_equip_list = bag_model.equip_list;
                var is_ok_task_lv_ten = true;
                var lv_list = [];
                _.some(bag_equip_list, function (equip_item) {
                    lv_list.push(equip_item.refine_lv);
                });
                var min = _.min(lv_list);

                // 任务统计全部装备达到10级
                taskService.addHeroEquiLvTotal(player_manager, min);

                // 任务统计装备升级次数
                taskService.addCompleteHeroEquitUp(player_manager);

                // 刷新战力
                roleService.updateHeroPower(player_manager);

                // 增加任务统计
                taskService.addUpgradeEquip(player_manager);
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK
            });
        }
    );
};

/**
 * 获得精炼需要消化的金币
 */
var _getRefineNeedGold = function (lv) {
    var refine_conf = equipConf.getEquipLvConf(lv);
    if (!refine_conf) {
        return 0;
    }
    return refine_conf.cost_gold;
};

/**
 * 获取装备等级对应的是否可进阶标志
 */
var _getUpgradeAdvanced = function (lv) {
    var refine_conf = equipConf.getEquipLvConf(lv);
    if (!refine_conf) {
        return 0;
    }
    return refine_conf.if_advanced;
};
